<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    //获取Validator报错
    public function getValidatorError($object){
        foreach ($object->all() as $error) {
            if (!empty($error)) return $error;
        }
    }

    //curl请求获取数据 get方式
    public function curl_request($url,$postdata = [],$timeout = 10){
        if (empty($url)) {
            return false;
        }
        //初始化curl
        $con = curl_init();
        //设置请求地址
        curl_setopt($con,CURLOPT_URL,$url);
        //返回结果不带header
        curl_setopt($con,CURLOPT_HEADER,false);
        //请求有效时间
        curl_setopt($con,CURLOPT_TIMEOUT,(int)$timeout);
        //获取的信息以文件流的形式返回，而不是直接输出
        curl_setopt($con,CURLOPT_RETURNTRANSFER,1);
        //强制协议为1.0
        curl_setopt($con, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        if (!empty($postdata)) {
            $postdata = http_build_query($postdata);
            //是否post提交
            curl_setopt($con,CURLOPT_POST,1);
            //提交post参数
            curl_setopt($con,CURLOPT_POSTFIELDS,$postdata);
        }
        $result = curl_exec($con);
        if (curl_errno($con)) {
            return curl_error($con);
        }
        return $result;
    }

    //对象转化成数组
    public function objectToArr($object){
        return json_decode(json_encode($object),true);
    }
}
